const apiUrl = 'https://mdcubs.top';

let openID =wx.getStorageSync('openID')
// 利用队列处理并发问题
const loginQueue = [];
let isLoginning = false;
/**
 * 
 * @param undefined 
 * @returns [promise] res 
 */
function login(){
  return new Promise((res,rej)=> {
    wx.login({
      success(r1){  
        // 获取openID
        if(r1.code) {
          requestP({
            url:`/xcx_openID_Servlet/get_xcx_openID_by_code`,
            data:{
              code: r1.code
            },
            method:'GET'
          })
            .then((res2)=> {
              // 证明登录成功获取成功openID
              const { State, xcx_openID } = res2
              if(State) {
                wx.setStorage({
                  key:"openID",
                  data:xcx_openID
                })
                let openID =wx.getStorageSync('openID');
                res(openID)
              }else{
                rej({
                  msg:'获取openID失败',
                  detail:res2
                })
              }
            })
        }
      }
    })
  })
}

/**
 * 获取openID
 * @param {*} undefined 
 * @returns [promise]openID
 */
function getOpenID() {
  return new Promise((resolve,reject)=> {
    // 本地openID缺失登录
    if(openID === '') {
      loginQueue.push({ resolve, reject })
      if(!isLoginning) {
        isLoginning = true;
        login()
          .then((res)=> {
            isLoginning = false;
            while (loginQueue.length) {
              loginQueue.shift().resolve(res)
            }
          })
          .catch((err) => {
            isLoginning = false;
            while (loginQueue.length) {
              loginQueue.shift().reject(err);
            }
          });
      }
        
      }
      else{
        resolve(openID)
      }
  })
}

/**
 * 判断请求状态是否成功
 * 参数：http状态码
 * 返回值：Boolean
 */
function isHttpSuccess(status) {
  return status >= 200 && status < 300 || status === 304;
}

/**
 * wx.request封装
 * @param {any} [Object]option = {}'
 * [Boolean]keepLogin = false 判断openID是否过期
 * @returns [promise]res
*/
function request(options = {}, keepLogin = true) {
  if (keepLogin) {
    return new Promise((res, rej) => {
      getOpenID()
        .then((r1) => {
          // 获取openId成功之后，发起请求
          // 判断是否只是需要传输openID
          if(options.data){
            options.data = Object.assign(options.data,{xcx_openID:r1})
          }else{
            options.data = Object.assign({},{xcx_openID:r1})
          }
          requestP(options)
            .then((r2) => {
              res(r2)
            })
            .catch(rej);
        })
        .catch(rej);
    });
  } else {
    // 不需要openID，直接发起请求
    return requestP(options);
  }
}


function requestP(options = {}) {
  const {
    success,
    fail,
    url
  } = options;
  options.url = apiUrl + url;
  return new Promise((res, rej)=> {
    wx.request(
      Object.assign(
      {},
      options,
      {
        header:{
          "cache-contorl":"86400"
        },
        success(r) {//成功请求的状态
          const isSuccess = isHttpSuccess(r.statusCode);
          if(isSuccess) {
            res(r.data);
          }else{
            rej({
              msg:`网络错误:${r.statusCode}`,
              detail:r
            });
          }
        },
        fail:rej,
      }
    ))
  })
}


module.exports = request
